//
//  PresentContainerViewController.swift
//  taurus
//
//  Created by 刘艺 on 2021/8/16.
//  Copyright © 2021 com.fiture. All rights reserved.
//

import UIKit

final class FiturePresentContainerViewController: UIViewController {
    
    // MARK: - 属性
    private var containerView: FitureChildrenContainerView?
    private var transitionController: FitureCustomInteractiveTransition = FitureCustomInteractiveTransition()
    private var config: FitureCustomPresentConfig = FitureCustomPresentConfig()
    private var maskViewTapBlock: (() -> Void)?
    private weak var childrenViewController: UIViewController?
    weak var delegate: FiturePresentContainerVCDismissDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        maskViewTapBlock = { [weak self] in
            guard let self = self else { return }
            self.customDismiss()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if config.needWrapNav {
            navigationController?.navigationBar.isHidden = true
        }
    }
    
    /// 点击 FitureChildrenContainerView 外的区域会dismiss
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        guard config.needWrapNav,
              let container = containerView,
              let v = touches.first?.view,
              !v.isDescendant(of: container) else { return }
        customDismiss()
    }

    deinit {
        print("------ deinit ----- FiturePresentContainerViewController")
    }

    // MARK: - 私有方法
    func configContainer(childrenViewController childrenVC: UIViewController,
                         config: FitureCustomPresentConfig = FitureCustomPresentConfig()) {
        transitionController.wireToViewController(viewController: self, config: config)
        self.childrenViewController = childrenVC
        self.config = config
        if config.needNav {
            let nav = FitureCustomPresentNaigationController(rootViewController: childrenVC)
            addChild(nav)
            containerView = FitureChildrenContainerView(naviView: nav.view, config: config)
            childrenVC.navigationItem.title = config.title
            if config.needCloseBtn {
                childrenVC.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_nav_close"), style: .plain, target: self, action: #selector(customDismiss))
            }
        } else {
            addChild(childrenVC)
            containerView = FitureChildrenContainerView(presentedView: childrenVC.view, config: config)
            containerView?.clikedDismiss = { [weak self] in
                guard let self = self else { return }
                self.customDismiss()
            }
        }
        if let container = containerView {
            view.addSubview(container)
            if !config.needWrapNav {
                container.snp.makeConstraints { m in
                    m.edges.equalToSuperview()
                }
            }
        }
    }

    func configContainer(subView subview: UIView,
                         config: FitureCustomPresentConfig = FitureCustomPresentConfig()) {
        let vc = UIViewController()
        vc.view.addSubview(subview)
        self.configContainer(childrenViewController: vc, config: config)
        subview.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    @objc func customDismiss() {
        delegate?.willDismiss()
        self.dismiss(animated: true) {
            [weak self] in
            guard let self = self else { return }
            self.delegate?.didDismiss()
            // 兜底的取消引用
            self.childrenViewController?.view.subviews.forEach { $0.removeFromSuperview() }
            self.childrenViewController?.removeFromParent()
            self.removeFromParent()
        }
    }

    @objc func customInteractiveDismiss() {
        self.delegate?.didDismiss()
        // 兜底的取消引用
        self.childrenViewController?.view.subviews.forEach { $0.removeFromSuperview() }
        self.childrenViewController?.removeFromParent()
        self.removeFromParent()
    }
}

// MARK: - UIViewControllerTransitioningDelegate
extension FiturePresentContainerViewController: UIViewControllerTransitioningDelegate {

    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        if config.needWrapNav {
            return FitureCustomPresentNaviAnimation(config: config)
        }
        return FitureCustomPresentAnimation(config: config, maskTapHandler: maskViewTapBlock)
    }

    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return FitureCustomDismissAnimation(config: config)
    }

    func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
        return transitionController.interacting ? self.transitionController : nil
    }
}

/// ps：暂未使用
protocol FiturePresentContainerVCDismissDelegate: AnyObject {

    func willDismiss()

    func didDismiss()
}

